package com.heihei.itextdemo.util.dto;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heihei.itextdemo.dto.PaginationInfo;
import com.heihei.itextdemo.dto.TableQueryParamDTO;

import java.util.List;

/**
 * @Description:分页工具类 - 针对mybatis-plus 使用
 * @Author: sunboqiang
 * @Company: 洛阳图联科技有限公司
 * @Date: 2019/10/31 9:13
 */
public class SmartPaginationUtil {

    public static <T> PaginationInfo<T> convert2PageInfoDTO(Page<T> page) {
        PaginationInfo<T> result = new PaginationInfo<>();
        result.setTotal(Long.valueOf(page.getTotal()));
        result.setRecords(page.getRecords());
        return result;
    }

    public static <T> Page<T> convert2PageQueryInfo(TableQueryParamDTO baseDTO) {
        Page<T> page = new Page<>();
        page.setCurrent(baseDTO.getPage());
        page.setSize(baseDTO.getRows());
        return page;
    }

    /**
     * @Description:转换为 PageResultDTO 对象
     * @Author: sunboqiang
     * @Date: 2019/10/31 9:40
     */
    public static <T, E> PaginationInfo<T> convert2PageInfoDTO(Page page, List<E> sourceList, Class<T> targetClazz) {
        PaginationInfo pageResultDTO = setPage(page);
        List<T> records = BeanUtil.copy(sourceList, targetClazz);
        page.setRecords(records);
        pageResultDTO.setRecords(records);
        return pageResultDTO;
    }

    /**
     * 转换为 PageResultDTO 对象
     */
    public static <T, E> PaginationInfo<T> convert2PageInfoDTO(Page page, List<E> sourceList) {
        PaginationInfo pageResultDTO = setPage(page);
        page.setRecords(sourceList);
        pageResultDTO.setRecords(sourceList);
        return pageResultDTO;
    }

    /**
     * 转换为 PageResultDTO 对象
     */
    public static <T, E> PaginationInfo<T> convert2PageInfoDTO(IPage page, Class<T> targetClazz) {
        PaginationInfo pageResultDTO = new PaginationInfo();
        pageResultDTO.setTotal(page.getTotal());
        List<T> records = BeanUtil.copy(page.getRecords(), targetClazz);
        pageResultDTO.setRecords(records);
        return pageResultDTO;
    }

    private static PaginationInfo setPage(Page page) {
        PaginationInfo pageResultDTO = new PaginationInfo();
        pageResultDTO.setTotal(Long.valueOf(page.getTotal()));
        return pageResultDTO;
    }
}
